const { statusBarHeight } = wx.getWindowInfo();
const app = getApp();
var ctx;
//导入验证js
import WxValidate from "../../../utils/WxValidate";
Page({
  data: {
    notLoggedIn: true,//是否未登录
    showLogOff: false,//退出登录弹窗
    tabbarIndex: 1,//1:登录 2:注册
    statusBarHeight: statusBarHeight,
    text: '',//验证码数据
    form: {//增加form子元素
      account: '',//账号
      password: ''//密码
    },
    registerForm: {
      type: '1',//注册类别1:个人 2法人
      account: '',//账号
      password: '',//密码
      confirmPassword: '',//确认密码
      unitName: '',//单位名称
      creditCode: '',//统一社会信用代码
      userName: '',//联系人姓名
      userPhone: '',//联系人电话
      verificationCode: ''//验证码
    },
    dataMsg: {
      accountMsg: '',
      passwordMsg: ''
    },
    registerDataMsg: {
      accountMsg: '',
      passwordMsg: '',
      confirmPasswordMsg: '',
      unitNameMsg: '',//单位名称
      creditCodeMsg: '',//统一社会信用代码
      userNameMsg: '',//联系人姓名
      userPhoneMsg: '',//联系人电话
      verificationCodeMsg: ''//验证码
    }
  },

  onLoad() {
    this.initValidate(this.data.tabbarIndex);
    var that = this;
    this.drawPic(that);
  },
  onShow() {

  },
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },//验证函数
  initValidate(index) {
    // 验证字段的规则
    const rules = {
      account: {
        required: true,
        maxlength: 15,
      },
      password: {
        required: true,
        password: true,
        minlength: 8,
        maxlength: 15,
      },
      confirmPassword: {
        required: index == 2 ? true : false,
        password: true,
        minlength: 8,
        maxlength: 15,
        equalTo: 'password',
      },
      unitName: {
        required: this.data.registerForm.type == 2 && index == 2 ? true : false,
        maxlength: 30,
      },
      creditCode: {
        required: this.data.registerForm.type == 2 && index == 2 ? true : false,
      },
      userName: {
        required: index == 2 ? true : false,
        maxlength: 10,
      },
      userPhone: {
        required: index == 2 ? true : false,
      },
      verificationCode: {
        required: index == 2 ? true : false,
        verificationCode: true
      }
    }
    const messages = {
      account: {
        required: '请输入账号',
        maxlength: '账号长度不多于15位',
      },
      password: {
        required: '请输入密码',
        minlength: '密码长度不少于8位',
        maxlength: '密码长度不多于15位',
        password: '密码中必须包含字母、数字，至少8个字符'
      },
      confirmPassword: {
        required: '请输入确认密码',
        minlength: '密码长度不少于6位',
        maxlength: '密码长度不多于15位',
        password: '密码中必须包含字母、数字，至少8个字符',
        equalTo: '确认密码和新密码保持一致',
      },
      unitName: {
        required: '请输入单位名称',
        maxlength: '单位名称长度不多于30位',
      },
      creditCode: {
        required: '请输入统一社会信用代码',
      },
      userName: {
        required: '请输入联系人姓名',
        maxlength: '联系人姓名长度不多于10位',
      },
      // assistance: {
      //   required: '请勾选1-2个敲码助手',
      // },
      userPhone: {
        required: '请输入联系人电话',
        phone: '请输入正确的电话号码格式',
      },
      verificationCode: {
        required: '请输入验证码',
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
    // 自定义验证规则
    this.WxValidate.addMethod('verificationCode', (value, param) => {
      this.setData({
        'registerDataMsg.verificationCodeMsg': ''
      })
      return this.WxValidate.optional(value) || (value.toLowerCase() == this.data.text.toLowerCase())
    }, '验证码不正确')
  },
  radioChange(e) {
    const value = e.detail.value
    const radio = this.data.radio
    const items = radio.map(n => {
      return Object.assign({}, n, {
        checked: n.value === value,
      })
    })
    this.setData({
      radio: items,
      'form.gender': value,
    })
  },
  checkboxChange(e) {
    const values = e.detail.value
    const checkbox = this.data.checkbox
    const items = checkbox.map(n => {
      return Object.assign({}, n, {
        checked: values.includes(n.value),
      })
    })
    this.setData({
      checkbox: items,
      'form.assistance': values,
    })
  },
  //调用验证函数(登录)
  formSubmit: function (e) {

    console.log('form发生了submit事件，携带的数据为：', e.detail.value)
    // 重置校验
    this.setData({
      'dataMsg.accountMsg': '',
      'dataMsg.passwordMsg': ''
    })
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList
      console.log(error)
      // 验证错误弹窗
      // this.showModal(error)
      error.filter((item) => {
        let itemName = 'dataMsg.' + item.param + 'Msg'
        this.setData({
          [itemName]: item.msg
        })
      })

      return false
    }
    // 显示登录后的界面
    // this.setData({ 'notLoggedIn': false });
    this.showModal({
      msg: '提交成功'
    })
  },
  // 监听数值变化(登录)
  changeValue(e) {

    let name = e.currentTarget.dataset.name
    let itemName = 'form.' + name
    this.setData({//把输入框的值存储(绑定)到变量inputValue中
      [itemName]: e.detail.value
    });
    const params = this.data.form
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList
      error.filter((item) => {
        // 只动态判断正在编辑的项
        if (item.param == name) {
          let itemName = 'dataMsg.' + item.param + 'Msg'
          this.setData({
            [itemName]: item.msg
          })
        }
      })
    }
  },

  //调用验证函数(注册)
  formRegister: function (e) {
    console.log('form发生了submit事件，携带的数据为：', e.detail.value)
    // 重置校验
    this.setData({
      'registerDataMsg.accountMsg': '',
      'registerDataMsg.passwordMsg': '',
      'registerDataMsg.confirmPasswordMsg': '',
      'registerDataMsg.unitNameMsg': '',
      'registerDataMsg.creditCodeMsg': '',
      'registerDataMsg.userNameMsg': '',
      'registerDataMsg.userPhoneMsg': '',
      'registerDataMsg.verificationCodeMsg': '',
    })
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList
      console.log(error)
      // this.showModal(error)
      error.filter((item) => {
        let itemName = 'registerDataMsg.' + item.param + 'Msg'
        this.setData({
          [itemName]: item.msg
        })
      })
      var that = this;
      this.drawPic(that);
      return false
    }
    this.showModal({
      msg: '提交成功'
    })
  },
  // 监听数值变化(注册)
  changeRegisterValue(e) {
    let name = e.currentTarget.dataset.name
    let itemName = 'registerForm.' + name
    this.setData({//把输入框的值存储(绑定)到变量inputValue中
      [itemName]: e.detail.value
    });
    // 重置校验
    let itemNameMsg = 'registerDataMsg.' + name + 'Msg'
    this.setData({
      [itemNameMsg]: '',
    })
    const params = this.data.registerForm
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList
      error.filter((item) => {
        // 只动态判断正在编辑的项
        if (item.param == name) {
          let itemName = 'registerDataMsg.' + item.param + 'Msg'
          this.setData({
            [itemName]: item.msg
          })
        }
      })
    }
  },
  //登录/注册切换
  toItem(e) {
    let index = e.currentTarget.dataset.index
    this.initValidate(index)
    if (index == 2) {
      var that = this;
      this.drawPic(that);
    }
    this.setData({ tabbarIndex: index });
  },
  // 注册类别切换
  typeChange(e) {
    this.setData({
      'registerDataMsg.accountMsg': '',
      'registerDataMsg.passwordMsg': '',
      'registerDataMsg.confirmPasswordMsg': '',
      'registerDataMsg.unitNameMsg': '',
      'registerDataMsg.creditCodeMsg': '',
      'registerDataMsg.userNameMsg': '',
      'registerDataMsg.userPhoneMsg': '',
      'registerDataMsg.verificationCodeMsg': '',
    })
    this.setData({ 'registerForm.type': e.detail.value });
    this.initValidate(2)
  },
  randomNum(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
  },
  /**生成一个随机色**/
  randomColor(min, max) {
    let r = this.randomNum(min, max);
    let g = this.randomNum(min, max);
    let b = this.randomNum(min, max);
    return "rgb(" + r + "," + g + "," + b + ")";
  },
  /**绘制验证码图片**/
  drawPic(that) {
    ctx = wx.createCanvasContext('canvas');
    /**绘制背景色**/
    ctx.fillStyle = this.randomColor(180, 240); //颜色若太深可能导致看不清
    ctx.fillRect(0, 0, 90, 34)
    /**绘制文字**/
    var arr;
    var text = '';
    var str = 'ABCEFGHJKLMNPQRSTWXY123456789';
    for (var i = 0; i < 4; i++) {
      var txt = str[this.randomNum(0, str.length)];
      ctx.fillStyle = this.randomColor(50, 160); //随机生成字体颜色
      ctx.font = this.randomNum(20, 26) + 'px SimHei'; //随机生成字体大小
      var x = 5 + i * 20;
      var y = this.randomNum(20, 25);
      var deg = this.randomNum(-20, 20);
      //修改坐标原点和旋转角度
      ctx.translate(x, y);
      ctx.rotate(deg * Math.PI / 180);
      ctx.fillText(txt, 5, 0);
      text = text + txt;
      //恢复坐标原点和旋转角度
      ctx.rotate(-deg * Math.PI / 180);
      ctx.translate(-x, -y);
    }
    /**绘制干扰线**/
    for (var i = 0; i < 4; i++) {
      ctx.strokeStyle = this.randomColor(40, 180);
      ctx.beginPath();
      ctx.moveTo(this.randomNum(0, 90), this.randomNum(0, 28));
      ctx.lineTo(this.randomNum(0, 90), this.randomNum(0, 28));
      ctx.stroke();
    }
    /**绘制干扰点**/
    for (var i = 0; i < 20; i++) {
      ctx.fillStyle = this.randomColor(0, 255);
      ctx.beginPath();
      ctx.arc(this.randomNum(0, 90), this.randomNum(0, 28), 1, 0, 2 * Math.PI);
      ctx.fill();
    }
    ctx.draw(false, function () {
      that.setData({
        text: text
      })
    });
  },
  // 刷新验证码
  change() {
    var that = this;
    this.drawPic(that);
  },
  toUserEdit() {
    wx.navigateTo({
      url: `/pages/usercenter/userEdit/userEdit`,
    });
  },
  //注销登录
  logOff() {
    console.log(1111)
    this.setData({
      'showLogOff': true
    })
  },
  closeDialog(e) {
    console.log(6666, e.type)
    this.setData({ 'showLogOff': false });
    if (e.type == "confirm") {
      this.setData({ 'notLoggedIn': true });
    }
  },

  // 复制
  copyBtn(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.ordernum,
      success: function (res) {
        wx.showToast({
          title: '联系方式已复制',
          icon: 'none'
        });
      }
    })
  },
})
